import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Form, Input, Button, Modal, DatePicker } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import moment from 'moment';

import FormItem from 'antd/es/form/FormItem';
import {
  CreateCoupon,
  createCouponAPI,
  DataType,
  GetCoupon,
  getCouponAPI,
  getUserAPI,
} from '@/service/coupon';
import { number } from 'echarts';

const queryPage: GetCoupon = {
  current: 1,
  size: 10,
  restaurantId: 0,
  sortField: '',
  sortOrder: '',
};

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { Search } = Input;

const App: React.FC = () => {
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const restaurantId = localStorage.getItem('restaurant');
  queryPage.restaurantId = restaurantId == null ? 0 : Number(restaurantId);

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '优惠券名称',
        dataIndex: 'title',
        sorter: true,
        render: (title) => `${title}`,
        width: '10%',
      },
      {
        title: '折扣',
        dataIndex: 'discount',
        render: (discount) => `${discount}`,
        width: '10%',
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        sorter: true,
        render: (startTime) => `${startTime}`,
        width: '20%',
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        sorter: true,
        render: (endTime) => `${endTime}`,
        width: '20%',
      },
      {
        title: '操作',
        width: '15%',
        render: (_, record) => {
          if (
            moment(record.endTime).format('YYYY-MM-DD') <
            moment().format('YYYY-MM-DD')
          ) {
            return <Button disabled>已过期</Button>;
          } else {
            return <Button>停用</Button>;
          }
        },
      },
      {
        title: '查看领取用户',
        width: '15%',
        render: (_, record) => {
          return <Button onClick={() => getUserList(record.id)}>查看</Button>;
        },
      },
    ],
    [],
  );

  const getUserList = async (id: number) => {
    const res = await getUserAPI(id);
    debugger;
    Modal.info({
      title: '领取用户',
      content: (
        <Table
          columns={[
            {
              title: '用户名',
              dataIndex: 'userName',
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: (status) => {
                if (status === 0) {
                  return '未使用';
                } else {
                  return '已使用';
                }
              },
            },
          ]}
          dataSource={res}
          pagination={false}
        />
      ),
    });
  };
  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    try {
      const res = await getCouponAPI(queryPage);
      setData(res.records);
      setTableParams((prevParams) => ({
        ...prevParams,
        pagination: {
          current: res.current,
          pageSize: res.size,
          total: res.total,
          ...prevParams.pagination,
        },
      }));
    } finally {
      setLoading(false);
    }
  }, [tableParams]);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams)]);

  //监听queryPage的变化
  const handleTableChange = useCallback(
    (
      pagination: TablePaginationConfig = {},
      filters: Record<string, FilterValue> = {},
      sorter: SorterResult<DataType> = {},
    ) => {
      setTableParams({
        pagination,
        filters,
        ...sorter,
      });
      queryPage.current = (pagination && Number(pagination.current)) || 1;
      queryPage.size = (pagination && Number(pagination.pageSize)) || 10;
      //如果为undefined则转换为'' String类型
      queryPage.sortField = sorter && sorter.field ? String(sorter.field) : '';
      queryPage.sortOrder =
        sorter && sorter.order === 'descend'
          ? 'desc'
          : sorter && sorter.order === 'ascend'
          ? 'asc'
          : '';
    },
    [tableParams],
  );
  const { RangePicker } = DatePicker;
  const [form] = Form.useForm();
  const onFinish = async (values: CreateCoupon) => {
    const id = localStorage.getItem('restaurant');
    const coupon = {
      title: values.title,
      rId: 1,
      description: values.description,
      discount: values.discount,
      startTime: moment(values.dateTime[0]).format('YYYY-MM-DD'),
      endTime: moment(values.dateTime[1]).format('YYYY-MM-DD'),
    };
    await createCouponAPI(coupon);
    fetchData();
  };
  const addSeat = () => {
    Modal.confirm({
      title: '新增优惠券',
      //from表单
      content: (
        <Form form={form} name="basic" onFinish={onFinish}>
          <FormItem label="优惠券标题" name="title">
            <Input />
          </FormItem>
          <FormItem label="优惠券描述" name="description">
            <Input />
          </FormItem>
          <FormItem label="折扣" name="discount">
            <Input />
          </FormItem>
          <FormItem label="选择时间" name="dateTime">
            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </FormItem>
        </Form>
      ),
      onOk: () => {
        form.submit();
      },
    });
  };

  return (
    <div>
      <Button onClick={addSeat}>新增优惠券</Button>

      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        pagination={tableParams.pagination}
        scroll={{ y: 530 }}
      />
    </div>
  );
};
export default App;
